package com.istock.user.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.PageInfo;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.base.serializer.json.TypeReference;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.model.Constants;
import com.istock.union.user.model.DictDataInfo;
import com.istock.union.user.model.DictTypeData;
import com.istock.union.user.model.DictTypeInfo;
import com.istock.union.user.model.DictTypeQuery;
import com.istock.union.user.model.OperLog;
import com.istock.union.user.model.SecurityChecker;
import com.istock.union.user.service.DictInfoService;

@Controller
@RequestMapping("/s/dictInfo")
public class DictInfoController {

	@Autowired
	private DictInfoService dictInfoService;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@RequestMapping("showList")
	@SecurityChecker("user:dictInfo:search")
	@OperLog(functionName="查询" , menuName ="字典管理")
	public String showList(ModelMap model) {
		return "user-app/dictInfo/list";
	}
	
	@RequestMapping("search")
	@SecurityChecker("user:dictInfo:search")
	public @ResponseBody ApiBaseResponse<PageInfo<DictTypeInfo>> search(ModelMap model , DictTypeQuery typeQuery , PageInfo<DictTypeInfo> pageInfo){
		if(pageInfo == null) {
			pageInfo = new PageInfo<DictTypeInfo>();
		}
		dictInfoService.findTypeList(typeQuery, pageInfo);
		return new ApiBaseResponse<PageInfo<DictTypeInfo>>(RetStatusEnum.SUCCESS, Constants.API_RESPONSE_SUCCESS_CODE, Constants.API_RESPONSE_SUCCESS_MESSAGE, pageInfo);
	}
	
	private static String EDIT_DICT_CACHE_ID = "EDIT_DICT_ID";
	
	@RequestMapping("addPre")
	@SecurityChecker("user:dictInfo:add")
	@OperLog(functionName="新增" , menuName ="字典管理")
	public String addPre(ModelMap model) {
		DictTypeData cacheObject = new DictTypeData();
		SSOClientUtils.getInstance().putObject(EDIT_DICT_CACHE_ID, cacheObject);
		model.put("edit", cacheObject);
		return "user-app/dictInfo/save";
	}
	
	@RequestMapping("editPre")
	@OperLog(functionName="编辑" , menuName ="字典管理")
	@SecurityChecker("user:dictInfo:edit")
	public String editPre(ModelMap model , String id) {
		if(StringUtils.isNotBlank(id)) {
			DictTypeData typeData = dictInfoService.findTypeById(id);
			SSOClientUtils.getInstance().putObject(EDIT_DICT_CACHE_ID, typeData);
			model.put("edit", typeData);
		}
		return "user-app/dictInfo/save";
	}
	
	@RequestMapping("checkDictTypeUnique")
	public @ResponseBody ApiBaseResponse<Boolean> checkDictTypeUnique(String id , String dictType){
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS , Constants.API_RESPONSE_SUCCESS_CODE, Constants.API_RESPONSE_SUCCESS_MESSAGE, dictInfoService.checkDictTypeUnique(id, dictType));
	}
	
	@RequestMapping("save")
	@OperLog(functionName="保存" , menuName="字典管理")
//	@SecurityChecker("")
	public @ResponseBody ApiBaseResponse<Boolean> save(DictTypeInfo typeInfo){
		try {
			DictTypeData cacheObject = SSOClientUtils.getInstance().getObject(EDIT_DICT_CACHE_ID , new TypeReference<DictTypeData>() {});
			BeanUtils.copyProperties(typeInfo, cacheObject);
			
			dictInfoService.saveDictTypeData(cacheObject);
			
			return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS, Constants.API_RESPONSE_SUCCESS_CODE, Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
		}catch(Exception e) {
			logger.error("save dict type exception " , e);
		}
		return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL, Constants.API_RESPONSE_FAIL_CODE, Constants.API_RESPONSE_FAIL_MESSAGE, false);
	}
	
	@RequestMapping("remove")
	@SecurityChecker("user:dictInfo:remove")
	@OperLog(functionName="删除",menuName="字典管理")
	public @ResponseBody ApiBaseResponse<Boolean> remove(ModelMap model , String[] ids){
		dictInfoService.removeTypes(ids);
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS, Constants.API_RESPONSE_SUCCESS_CODE, Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
	}
	
	@RequestMapping("searchDictData")
	public @ResponseBody ApiBaseResponse<PageInfo<DictDataInfo>> searchDictData(ModelMap model){
		DictTypeData cacheObject = SSOClientUtils.getInstance().getObject(EDIT_DICT_CACHE_ID , new TypeReference<DictTypeData>() {});
		if(cacheObject != null) {
			PageInfo<DictDataInfo> pageInfo = new PageInfo<DictDataInfo>();
			pageInfo.setData(cacheObject.getDataList());
			return new ApiBaseResponse<PageInfo<DictDataInfo>>(RetStatusEnum.SUCCESS, Constants.API_RESPONSE_SUCCESS_CODE, Constants.API_RESPONSE_SUCCESS_MESSAGE, pageInfo);
		}
		return new ApiBaseResponse<PageInfo<DictDataInfo>>(RetStatusEnum.SUCCESS, Constants.API_RESPONSE_FAIL_CODE, "无法找到编辑字典类型的字典项", null);
	}
	
	@RequestMapping("addDataPre")
	public String addDataPre(ModelMap model) {
		return "user-app/dictInfo/dataSave";
	}
	
	@RequestMapping("editDataPre")
	public String editDataPre(ModelMap model , String id) {
		if(StringUtils.isNotBlank(id)) {
			DictTypeData cacheObject = SSOClientUtils.getInstance().getObject(EDIT_DICT_CACHE_ID , new TypeReference<DictTypeData>() {});
			for(DictDataInfo dataInfo : cacheObject.getDataList()) {
				if(dataInfo.getId().equalsIgnoreCase(id)) {
					model.put("edit", dataInfo);
					break;
				}
			}
		}
		return "user-app/dictInfo/dataSave";
	}
	
	@RequestMapping("saveData")
	public @ResponseBody ApiBaseResponse<Boolean> saveData(ModelMap model , DictDataInfo dataInfo){
		DictTypeData cacheObject = SSOClientUtils.getInstance().getObject(EDIT_DICT_CACHE_ID , new TypeReference<DictTypeData>() {});
		dataInfo.setDictType(cacheObject.getDictType());
		if(StringUtils.isNotBlank(dataInfo.getId())) {
			for(DictDataInfo item : cacheObject.getDataList()) {
				if(item.getId().equalsIgnoreCase(dataInfo.getId())) {
					BeanUtils.copyProperties(dataInfo, item);
					break;
				}
			}
		}else {
			dataInfo.setId(""+(0 - Math.round(Math.random()*1000000000000L)));
			cacheObject.getDataList().add(dataInfo);
		}
		SSOClientUtils.getInstance().putObject(EDIT_DICT_CACHE_ID, cacheObject);
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
	}
	
	@RequestMapping("removeData")
	public @ResponseBody ApiBaseResponse<Boolean> removeData(ModelMap model , String[] ids){
		DictTypeData cacheObject = SSOClientUtils.getInstance().getObject(EDIT_DICT_CACHE_ID , new TypeReference<DictTypeData>() {});
		if(ids != null && ids.length>0) {
			List<DictDataInfo> newList = new ArrayList<DictDataInfo>();
			List<String> idList = Arrays.asList(ids);
			for(DictDataInfo dataInfo : cacheObject.getDataList()) {
				if(idList != null && !idList.contains(dataInfo.getId())) {
					newList.add(dataInfo);
				}
			}
			cacheObject.setDataList(newList);
		}
		SSOClientUtils.getInstance().putObject(EDIT_DICT_CACHE_ID, cacheObject);
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
	}
}
